<template>
    <div class="campaign-page">
        <span class="article-title">Campaign管理</span>
        <div class="fliter">
            <div style="display: flex;width: 100%;">
                <span class="filter-item">
                    <span style="font-size: 14px;">CampaignId：</span>
                    <el-select v-model="searchParmas.campaignId" style="width:100%;margin-right: 10px;" remote
                        filterable :remote-method="remoteCampaignId" :loading="campaignLoading"
                        placeholder="请输入CampaignId" clearable>
                        <el-option v-for="item in camOptions" :key="item.id" :label="item.siteName" :value="item.id" />
                    </el-select>
                </span>
                <span class="filter-item">
                    <div style="font-size: 14px;">CampaignName：</div>
                    <el-input v-model="searchParmas.campaignName" style="margin-right: 10px;"
                        placeholder="请输入Campaign名称" clearable></el-input>
                </span>
                <span class="filter-item">
                    <span style="font-size: 14px;">ChannelId:</span>
                    <el-input v-model="searchParmas.channelId" style="margin-right: 10px;" placeholder="请输入Channel ID"
                        clearable>
                    </el-input>
                </span>
                <span class="filter-item">
                    <div style="font-size: 14px;min-width: 70px;">文章ID： </div>
                    <el-select v-model="searchParmas.articleId" style="margin-right: 10px;" remote filterable
                        :remote-method="remoteArticleId" :loading="articleLoading" placeholder="请输入文章ID" clearable>
                        <el-option v-for="item in articleIdOptions" :key="item.id" :label="item.siteName"
                            :value="item.id" />
                    </el-select>
                </span>
            </div>
            <div style="display: flex;width: 100%;">
                <span class="filter-item">
                    <div style="font-size: 14px;min-width: 50px;">状态:</div>
                    <el-select v-model="searchParmas.status" style="margin-right: 10px;" placeholder="请选择状态" clearable>
                        <el-option v-for="item in statusOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </span>
                <span class="filter-item">
                    <div style="font-size: 14px;min-width: 50px;">网站:</div>
                    <el-select v-model="searchParmas.siteId" style=" margin-right: 10px;" placeholder="请选择网站" clearable>
                        <el-option v-for="item in siteOptions" :key="item.id" :label="item.siteName" :value="item.id" />
                    </el-select>
                </span>
                <span class="filter-item">
                    <div style="font-size: 14px;min-width: 50px;">生成者:</div>
                    <el-select v-model="searchParmas.createUserId" style=" margin-right: 10px;" placeholder="请选择生成者"
                        clearable filterable>
                        <el-option v-for="item in creatorOptions" :key="item.id" :label="item.username"
                            :value="item.id" />
                    </el-select>
                    <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
                    <el-button type="primary" :icon="RefreshRight" @click="handleReset">重置</el-button>
                </span>

            </div>
        </div>
        <div class="article-table">
            <el-button type="primary" @click="handleAddCampaign()">+ 添加Campaign</el-button>
            <el-table :data="tableData" v-loading="loading"
                :header-cell-style="{ background: '#fafafa', height: '56px', }"
                style="width: 100%;margin-top: 20px;margin-bottom: 20px; height: calc(100% - 70px);">
                <template v-for="(item, index) in tableHeader" :key="index">
                    <el-table-column :prop="item.prop" :label="item.label" :min-width="item.width" :fixed="index === 0">
                        <template #default="scope">
                            <div v-if="item.prop === 'image' && scope.row[item.prop]"
                                style="width: 120px; height: 100%;">
                                <el-image style="width: 100%; height: 100%" :src="scope.row[item.prop]" :zoom-rate="1.2"
                                    preview-teleported :preview-src-list="[scope.row[item.prop]]" :max-scale="7"
                                    :min-scale="0.2" fit="cover" />
                            </div>
                            <span v-else-if="item.prop === 'status'">{{ StatusMap[scope.row[item.prop]] }}</span>
                            <span v-else-if="item.prop === 'url'">
                                <a :href="scope.row[item.prop]" target="_blank">{{ scope.row[item.prop] }}</a>
                            </span>
                            <span v-else-if="item.prop === 'createTime' || item.prop === 'updateTime'">
                                {{ dayjs(scope.row[item.prop])?.format('YYYY-MM-DD HH:mm') }}
                            </span>
                            <span v-else>{{ scope.row[item.prop] }}</span>
                        </template>

                    </el-table-column>
                </template>
                <el-table-column label="操作" width="150" fixed="right">
                    <template #default="scope">
                        <div style="display: flex;align-items: center;gap: 15px;">
                            <span style="cursor: pointer;color: #1677ff;"
                                @click="handleCheck('check', scope.row.id)">查看</span>
                            <span style="cursor: pointer;color: #1677ff;"
                                @click="handleCheck('edit', scope.row.id)">编辑</span>
                            <span style="cursor: pointer;color: #1677ff;" v-if="scope.row?.status !== 3"
                                @click="handleArchived(scope.row.id)">归档</span>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize"
                style="display: flex;justify-content: end;" layout="total,prev, pager, next,sizes" :total="total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
        <CampaignAdd ref="campaignAdd" @getData="getCampaignData" />
    </div>
</template>

<script setup lang="ts">
import { defineComponent, nextTick, onActivated, ref, watch } from 'vue';
import CampaignAdd from '../components/campaignAdd.vue'
import { Search, RefreshRight, Loading } from '@element-plus/icons-vue'
defineComponent({ name: 'Campaign' })
import service from '../config';
import { useRoute } from 'vue-router';
import { dayjs, ElMessage } from 'element-plus';
const searchParmas = ref<{ campaignId: number, campaignName: string, channelId: string, articleId: number, status: number, siteId: number, createUserId: number }>({
    campaignId: null,
    campaignName: '',
    channelId: '',
    articleId: null,
    status: null,
    siteId: null,
    createUserId: null,
})
const pageNum = ref(1)
const pageSize = ref(10)
const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const route = useRoute()
const campaignAdd = ref<{ openModal: (type?: string, id?: number) => void }>()
const siteOptions = ref([])
const campaignLoading = ref()
const articleLoading = ref()

const articleIdOptions = ref([])
const camOptions = ref([])
const creatorOptions = ref([])
const statusOptions = ref([{ label: '通过', value: 1 }, { label: '驳回', value: 0 }, { label: '审核中', value: 2 }, { label: '已归档', value: 3 }])
enum StatusMap {
    驳回,
    通过,
    审核中,
    已归档,
}
const tableHeader = ref([
    { label: 'CampaignId', prop: 'id', width: 120 },
    { label: 'Campaign', prop: 'campaignName', width: 120 },
    { label: '投放标题', prop: 'refTitle', width: 200 },
    { label: '文章ID', prop: 'articleId', width: 120 },
    { label: '生成者', prop: 'creator', width: 150 },
    { label: '状态', prop: 'status', width: 80 },
    { label: '落地页URL', prop: 'url', width: 500 },
    { label: '投放渠道', prop: 'piSource', width: 120 },
    { label: '投放国家', prop: 'geos', width: 120 },
    { label: '创建时间', prop: 'createTime', width: 150 },
    { label: '更新时间', prop: 'updateTime', width: 150 },
])

const handleAddCampaign = () => {
    campaignAdd.value?.openModal('add')
}

const handleCheck = (type, id) => {
    campaignAdd.value?.openModal(type, id)
}

const getCampaignData = () => {
    loading.value = true
    service.post('/campaign/page', { pageNum: pageNum.value, pageSize: pageSize.value, ...searchParmas.value })
        .then(response => {
            loading.value = false
            tableData.value = response.data?.records
            total.value = response?.data?.total
        })
        .catch(error => {
            loading.value = false
            ElMessage.error(error)
        });
}

const handleSizeChange = () => {
    pageNum.value = 1
    getCampaignData()
}

const handleCurrentChange = () => {
    getCampaignData()
}

const handleSearch = () => {
    getCampaignData()
}

const handleReset = () => {
    searchParmas.value = {
        campaignId: null,
        campaignName: '',
        channelId: '',
        articleId: null,
        status: null,
        siteId: null,
        createUserId: null,
    }
    getCampaignData()
}

const handleDelete = (id: number) => {
    service.post('/campaign/delete', { id })
        .then(response => {
            ElMessage.success('删除成功！')
            getCampaignData()
        })
        .catch(error => {
            ElMessage.error(error)
        });
}

const handleArchived = (id: number) => {
    service.post('/campaign/campaignArchived', { id })
        .then(response => {
            ElMessage.success('归档成功！')
            getCampaignData()
        })
        .catch(error => {
            ElMessage.error(error)
        });
}

const getSite = () => {
    service.get('/site/getAll')
        .then(response => {
            siteOptions.value = response?.data
        })
        .catch(error => {
            console.error('Error fetching data:', error);
        });
}

const getCreatorList = () => {
    service.get('/user/getAll')
        .then(response => {
            creatorOptions.value = response?.data || []
        })
        .catch(error => {
            ElMessage.error(error?.message)
        });
}

const remoteCampaignId = (query: string) => {
    if (query) {
        campaignLoading.value = true
        service.post('/campaign/getAllIdBySearch', { id: query })
            .then(response => {
                campaignLoading.value = false
                camOptions.value = response.data?.ids
            })
            .catch(error => {
                campaignLoading.value = false
                ElMessage.error(error)
            });
    } else {
        camOptions.value = []
    }
}

const remoteArticleId = (query: string) => {
    if (query) {
        articleLoading.value = true
        service.post('/article/getAllIdBySearch', { id: query })
            .then(response => {
                articleLoading.value = false
                articleIdOptions.value = response.data?.ids
            })
            .catch(error => {
                articleLoading.value = false
                ElMessage.error(error)
            });
    } else {
        camOptions.value = []
    }
}

onActivated(() => {
    getSite()
    getCreatorList()
    getCampaignData()
})

watch(() => route.query.articleId, () => {
    nextTick(() => {
        if (route.query.articleId) {
            campaignAdd.value?.openModal('add', Number(route.query.articleId));
        }
    });
}, { immediate: true });
</script>

<style lang="scss">
.campaign-page {
    background-color: #fff;
    height: calc(100% - 4px);
    padding: 30px;
    width: 100%;
    box-sizing: border-box;

    .article-title {
        font-size: 20px;
        font-weight: 600;
    }

    .fliter {
        display: flex;
        flex-direction: column;
        gap: 25px;
        margin: 30px 0;

        .filter-item {
            display: flex;
            width: 33%;
            gap: 5px;
            align-items: center;
        }
    }

    a {
        text-decoration: none;
        color: #1677ff;
    }

    .el-button--primary {
        background-color: #1677ff;
    }

    .article-table {
        margin-top: 30px;
        height: calc(100% - 200px);
    }

    .el-drawer {
        width: 100% !important;
    }

    .el-drawer__body {
        padding: 0;
    }

    .el-table__row {
        font-size: 13px;
    }

}
</style>
